package dbdata

import (
	"reflect"
	"github.com/astaxie/beego/orm"
	"fmt"
	"cloud_worm/util/umodels/mysqldb"
	"time"
)

type WeaponAlertInfo struct {
	Id          int64
	Ip          string
	Name        string

	OptionId    int
	OptionName  string

	Result      int
	ExtraMsg    string
	Created     int64
	Updated     int64
	Status      int
}

func (w *WeaponAlertInfo) TableName() string {
	return reflect.TypeOf(*w).Name()
}

func (w *WeaponAlertInfo) Read(fields ...string) error {
	err := orm.NewOrm().Read(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WeaponAlertInfo) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WeaponAlertInfo) Insert() error {
	_, err := orm.NewOrm().Insert(w)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}

	return nil
}

func init()  {
	orm.RegisterModel(new(WeaponAlertInfo))
}

func (w *WeaponAlertInfo) SetInvalidByIPAndName(ip string, name string) error {
	o := orm.NewOrm()
	_, err := o.Raw("UPDATE `WolMachineAlertInfo` SET `status`=? WHERE `ip`=? AND `name`=?", mysqldb.StatusInvalid, ip, name).Exec()
	if err != nil {
		return err
	}
	return nil
}

func (w *WeaponAlertInfo) Select(offset int, limit int, status int, name string, ip string) ([]*WeaponAlertInfo, error) {

	var alerts []*WeaponAlertInfo

	qs := orm.NewOrm().QueryTable(w).Offset(offset).Limit(limit).OrderBy("option_id")

	if status != mysqldb.SelectIntAll {
		qs = qs.Filter("status", status)
	}
	if ip != mysqldb.SelectStrAll {
		qs = qs.Filter("ip", ip)
	}
	if name != mysqldb.SelectStrAll {
		qs = qs.Filter("name", name)
	}

	_, err := qs.All(&alerts)
	if err != nil {
		return nil, err
	}

	return alerts, nil
}

type AlertBriefInfo struct {
	OptionId    int
	OptionName  string
	Result      string
	ExtraMsg    string
	Updated     string
}

func (w *WeaponAlertInfo) SelectForAlertBriefInfo(offset int, limit int, status int, name string, ip string) ([]*AlertBriefInfo, error) {
	alertInfos, err := w.Select(offset, limit, status, name, ip)
	if err != nil {
		return nil, err
	}

	var alerts []*AlertBriefInfo
	for _, one := range alertInfos {
		alert := &AlertBriefInfo{
			OptionId: one.OptionId,
			OptionName: one.OptionName,
			ExtraMsg: one.ExtraMsg,
			Updated: time.Unix(one.Updated, 0).Format("2006-01-02 15:04:05"),
		}
		if one.Result == 0 {
			alert.Result = "失败"
		} else {
			alert.Result = "成功"
		}

		alerts = append(alerts, alert)
	}

	return alerts, nil
}

func (w *WeaponAlertInfo) AllCountByTimeDuration(startTime int64, endTime int64) (allCnt int64, timeCnt int64, err error) {
	if startTime >= endTime {
		return 0, 0, fmt.Errorf("input start_time(%d) and end_time(%d) error", startTime, endTime)
	}

	qs := orm.NewOrm().QueryTable(w)
	qs = qs.Filter("status", mysqldb.StatusValid)                                 // 全量的检查项
	allCnt, err = qs.Count()
	if err != nil {
		return allCnt, timeCnt, err
	}

	qs = qs.Filter("created__gt", startTime).Filter("created__lte", endTime)    // 检查项，增加时间段限制
	timeCnt, err = qs.Count()
	if err != nil {
		return allCnt, timeCnt, err
	}

	return allCnt, timeCnt, err
}

func (w *WeaponAlertInfo) FailedCountByTimeDuration(startTime int64, endTime int64) (allCnt int64, timeCnt int64, err error) {
	if startTime >= endTime {
		return 0, 0, fmt.Errorf("input start_time(%d) and end_time(%d) error", startTime, endTime)
	}

	qs := orm.NewOrm().QueryTable(w)
	qs = qs.Filter("status", mysqldb.StatusValid).Filter("result", 0)             // 全部的failed数
	allCnt, err = qs.Count()
	if err != nil {
		return allCnt, timeCnt, err
	}

	qs = qs.Filter("created__gt", startTime).Filter("created__lte", endTime)    // failed数检查项，增加时间段限制
	timeCnt, err = qs.Count()
	if err != nil {
		return allCnt, timeCnt, err
	}

	return allCnt, timeCnt, err
}